#!/usr/bin/env python3

import os
import sys
import pwd
import crypt
import getpass
import spwd

"su命令功能必须给python解析器加特权位才有效果"

def main(argv):
    username = 'root' if len(argv) < 2 else argv[1]

    pw = pwd.getpwnam(username)
    if os.getuid() != 0:
        inputPwd = getpass.getpass()
        pwdp = spwd.getspnam(username)
        newPwd = crypt.crypt(inputPwd, pwdp.sp_pwdp)
        if newPwd != pwdp.sp_pwdp:
            print("你不知道密码, 你想干什么??")
            return

    if os.fork() == 0:
        os.environ['HOME'] = pw.pw_dir
        os.environ['USER'] = username
        os.environ['USERNAME'] = username
        os.environ['LOGNAME'] = username

        os.chdir(pw.pw_dir)
        os.setgroups([pw.pw_gid])
        os.setgid(pw.pw_gid)
        os.setuid(pw.pw_uid)
        os.execlp(pw.pw_shell, pw.pw_shell)
    os.wait()

if __name__ == "__main__":
    main(sys.argv)
